/**
 * Created by zxh on 2016/12/12.
 */
import React from 'react';
import {
  Form,
  Col,
  Input,
  Button,
  DatePicker,
  Select,
  Table,
  Icon,
  Radio,
  InputNumber,
  Checkbox,
  Modal,
  message,
  notification,
  Affix,
  Upload
} from 'antd';

const FormItem = Form.Item;

class FieldConverter {

constructor() {
    this.converters = [];
  }

  addConverter(converter) {
    this.converters.push(converter);
  }

  extendConvert(option) {
    var fieldForm = null;

    for(var i=0;i<this.converters.length;i++)
    {
      fieldForm = this.converters[i].convert(option);
      if (fieldForm != null) {
        break;
      }
    }
    
    return fieldForm;
  }

  convert(obj, field) {
    var colWrapper = this.colWrapper;
    return this.internalConvert({ obj: obj, field: field, wrapper: colWrapper });
  }

  /**
   * 将schema中的一个字段转换为表单的一项
   *
   * @param field
   */
  internalConvert(option) {
    this.wrapperOption(option);
    const {getFieldProps, field, fieldOptions, wrapper, obj} = option;

    //obj.formData[field.key]
    // 对于主键, 直接返回一个不可编辑的textarea
    if (this.primaryKey === field.key) {
      logger.debug('key %o is primary, transform to text area', field);
      return wrapper((
        {...obj.props.form.getFieldDecorator(field.key)(<Input type="textarea" autosize={{ minRows: 1, maxRows: 10 }} disabled
          size="default"  />)}
      ), field);
    }

    var fieldItem = this.extendConvert(option);
    if (fieldItem != null)
      return fieldItem;
  }

  wrapperOption(option) {
    option.getFieldProps = option.obj.props.form.getFieldProps;
    var fieldOptions = {};
    if (option.field.rules) {
      fieldOptions.rules = option.field.rules;
    }
    if (option.field.initialValue) {
      fieldOptions.initialValue = option.field.initialValue;
    }

    if (option.field.valuePropName) {
      fieldOptions.valuePropName = option.field.valuePropName;
    }
    option.fieldOptions = fieldOptions;
  }

  colWrapper(formItem, field)
  {
    return null;
  }
}

export default FieldConverter;
